package socket.client.gui;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;

class ReadWriteThread implements Runnable {

    private final InputStream is;

    private final OutputStream os;

    private final MessageCallback msgCallback;

    private boolean isRunning;

    public ReadWriteThread(final InputStream is, final OutputStream os, final MessageCallback callback) {
        this.is = is;
        this.os = os;
        this.msgCallback = callback;
        isRunning = true;
    }

    @Override
    public void run() {
        final BufferedInputStream bis = new BufferedInputStream(is);
        while (isRunning) {
            try {
                final byte[] bytes = new byte[4096];
                bis.read(bytes);

                final String response = new String(bytes).intern().trim();
                if (!response.isEmpty()) {
                    msgCallback.onInbound(response);
                }
            } catch (final SocketException e) {
                msgCallback.onDisconnect();

            } catch (final Exception e) {
                e.printStackTrace();
                msgCallback.onException(e);
            }
        }
    }

    public void stop() {
        isRunning = false;
    }

    public void send(final String message) {
        try {
            os.write(message.getBytes());
            msgCallback.onOutbound(message);
            msgCallback.onMessageSent();

        } catch (final Exception e) {
            e.printStackTrace();
            msgCallback.onException(e);
        }
    }
    
    interface MessageCallback {

        void onMessageSent();
        
        void onException(Exception e);

        void onDisconnect();

        void onInbound(String message);

        void onOutbound(String message);
    }
    
}
